package sockethomework;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private Socket socket;

    public Client() {
        try {
            System.out.println("正在连接服务端");
            socket = new Socket("localhost", 8888);//三次握手
            System.out.println("服务端连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {

        SeverHandler severHandler = new SeverHandler();
        Thread t = new Thread(severHandler);
        t.start();

        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);

            Scanner scan = new Scanner(System.in);
            while (true) {
                System.out.println("请输入昵称");
                String nickName = scan.nextLine();
                if (nickName.trim().isEmpty()) {
                    System.out.println("昵称不能为空");
                } else {
                    pw.println(nickName);//将昵称发送给服务端
                    break;
                }
            }

            while (true) {
                String line = scan.nextLine();
                if ("exit".equalsIgnoreCase(line)) {
                    break;
                }
                pw.println(line);

            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();//四次挥手
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    private class SeverHandler implements Runnable {
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message = br.readLine()) != null) {
                    System.out.println(message);
                }
            } catch (IOException e) {
            }
        }
    }


}
